package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.MenuActivity;
import com.example.hcd.R;
import com.example.hcd.adapt.FileAdapter;
import com.example.hcd.datamanage.LoadedImage;
import com.example.hcd.datamanage.PeopleNextData;
import com.example.hcd.datamanage.ProjectChildData;
import com.example.hcd.datamanage.ReimburseData;
import com.example.hcd.datamanage.UserInfo;
import com.example.hcd.internet.FileUtils;
import com.example.hcd.internet.InternetKeep;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.CommonDialog;
import com.example.hcd.tool.DigitalTool;
import com.example.hcd.tool.MyGridView;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.ToastHelp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ReimburseApply extends BaseActivity implements OnClickListener
{

	private ReimburseApply context;

	private ReimburseData reimburseData;

	// 子项目数组
	ArrayList<ProjectChildData> childProjectList;

	// 现实金额的控件
	private EditText editText4;
	private EditText editText5;

	// // 项目下拉popwindows
	// private PopupWindow popipwindow;
	// // pop界面
	// private View popview;

	// 是否有发票下拉popwindows
	private CommonDialog commonDialog, commonDialog1;

	private View addline;
	private View reimburseView;
	// 下拉文字
	private TextView xialaEdit;

	// 下拉文字
	private TextView xialaEdit1;

	// 附件的GridView
	private MyGridView gridview;

	// 附件的地址集合
	private ArrayList<String> listfile = new ArrayList<String>();
	private ArrayList<String> listfileCatch = new ArrayList<String>();

	private FileAdapter fileAdapter;
	// 获取下一步处理人
	private ArrayList<PeopleNextData> peoples_next;
	private TextView nextPeople;

	private RelativeLayout nextPeopleBg;

	public final static int SELECT_RELATION = 14;

	private String Id = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mPageName = "ReimburseApply";
		// 初始化
		LayoutInflater inflater = LayoutInflater.from(this);
		context = this;
		reimburseView = inflater.inflate(R.layout.reimburse_apply_view, null);
		setContentView(reimburseView);

		// if(UserInfo.getUserInfor().isShenZhen())
		{
			RelativeLayout view = (RelativeLayout) reimburseView.findViewById(R.id.is_have_receipt);
			view.setVisibility(View.VISIBLE);

			xialaEdit1 = (TextView) reimburseView.findViewById(R.id.title52);
			xialaEdit1.setOnClickListener(this);
			RelativeLayout xialaimage = (RelativeLayout) reimburseView.findViewById(R.id.btn_image2);
			xialaimage.setOnClickListener(this);

			String[] texts = new String[] { " - - ", "无票", "有票" };
			commonDialog1 = new CommonDialog(this);
			for (int i = 0; i < texts.length; i++)
			{
				final View item = (View) inflater.inflate(R.layout.common_dialog_item, null);

				final TextView text = (TextView) item.findViewById(R.id.item_text);
				text.setText(texts[i]);
				commonDialog1.addView(item);
				xialaEdit1.setText(texts[0]);
				text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						xialaEdit1.setText(text.getText().toString());
						commonDialog1.dismiss();
					}
				});

			}

		}

		childProjectList = new ArrayList<ProjectChildData>();
		reimburseData = new ReimburseData(context);

		// popview = inflater.inflate(R.layout.my_popup_view, null);
		//
		// popipwindow = new PopupWindow(popview, LayoutParams.MATCH_PARENT,
		// LayoutParams.MATCH_PARENT);
		//
		// // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景（很神奇的）
		// popipwindow.setBackgroundDrawable(new BitmapDrawable());
		// 获取控件

		editText4 = (EditText) findViewById(R.id.editText4);
		editText5 = (EditText) findViewById(R.id.editText5);

		// 子项目的line
		addline = ((View) findViewById(R.id.addline));
		// 返回键
		ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
		// 提交键
		ImageView uploadBtn = (ImageView) findViewById(R.id.title_bar_btn_right);
		backBtn.setOnClickListener(context);
		uploadBtn.setOnClickListener(context);
		// 弹出下拉
		xialaEdit = (TextView) findViewById(R.id.title21);
		xialaEdit.setOnClickListener(context);

		initBaseInfo();
		findViewById(R.id.btn_image1).setOnClickListener(context);

		findViewById(R.id.imagebtn3).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				// TODO Auto-generated method stub

				final LinearLayout layout = (LinearLayout) addline;

				LayoutInflater inflater = LayoutInflater.from(context);
				final View item = (View) inflater.inflate(R.layout.edittext_info_money_item, null);

				final ProjectChildData childProject = new ProjectChildData();
				childProjectList.add(childProject);
				layout.addView(item);

				context.refreshMoney();
				// 添加编辑状态获取事件
				final EditText text1 = (EditText) item.findViewById(R.id.editText1);

				final EditText text2 = (EditText) item.findViewById(R.id.editText2);
				text1.addTextChangedListener(new TextWatcher() {

					@Override
					public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
					{
						// TODO Auto-generated method stub

					}

					@Override
					public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
					{
						// TODO Auto-generated method stub

					}

					@Override
					public void afterTextChanged(Editable arg0)
					{
						// TODO Auto-generated method stub
						childProject.info = text1.getText().toString();
					}
				});

				text2.addTextChangedListener(new TextWatcher() {

					private boolean isChanged;

					@Override
					public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
					{
						// TODO Auto-generated method stub

					}

					@Override
					public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
					{
						// TODO Auto-generated method stub

					}

					@Override
					public void afterTextChanged(Editable s)
					{
						// TODO Auto-generated method stub
						if (text2.getText().toString().equals("."))
						{
							return;
						}

						if (isChanged)
						{// ----->如果字符未改变则返回
							return;
						}
						String str = s.toString();

						isChanged = true;
						String cuttedStr = str;
						boolean flag = false;
						/* 删除字符串中的dot */
						for (int i = str.length() - 1; i >= 0; i--)
						{
							char c = str.charAt(i);
							if ('.' == c && i == str.length() - 4)
							{
								cuttedStr = str.substring(0, i + 3);
								if (cuttedStr.endsWith("."))
								{
									cuttedStr = cuttedStr.substring(0, i + 1);
								}
								flag = true;
								break;
							}
						}

						if (flag)
						{
							text2.setText(cuttedStr);
							// 设置新光标所在的位置
							Selection.setSelection((Editable) text2.getText(), cuttedStr.length());
						}

						str = text2.getText().toString();
						if (str.contains("."))
						{
							int numlength = 0;
							for (int i = 0; i < str.length() - 1; i++)
							{
								char c = str.charAt(i);
								if (c == '.')
								{
									break;
								} else
								{
									numlength++;
								}

							}
							if (numlength > 8)
							{
								int index = text2.getSelectionStart();
								Editable editable = text2.getText();
								editable.delete(index - 1, index);
							}

						} else
						{
							if (str.length() > 8)
							{
								int index = text2.getSelectionStart();
								Editable editable = text2.getText();
								editable.delete(index - 1, index);
							}
						}

						if (text2.getText().toString() == null || text2.getText().toString().equals(""))
						{
							str = "0";
						} else
						{
							str = text2.getText().toString();

						}
						childProject.numOfmoney = Double.parseDouble(str);

						context.refreshMoney();
						isChanged = false;

					}
				});

				// 添加删除事件
				item.findViewById(R.id.sub_btn).setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						// TODO Auto-generated method stub
						layout.removeView(item);
						childProjectList.remove(childProject);
						context.refreshMoney();
					}
				});

			}
		});

		findViewById(R.id.imagebtn312).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				new IsHaveRelateBorrow().execute();
			}
		});

		setProgressBarIndeterminateVisibility(true);
		gridview = (MyGridView) reimburseView.findViewById(R.id.file_gridview);
		gridview.setVisibility(View.GONE);
		fileAdapter = new FileAdapter(this);
		gridview.setAdapter(fileAdapter);
		gridview.setHaveScrollbar(false);
		gridview.setOnItemLongClickListener(new OnItemLongClickListener() {
			// GridList长按了某项
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				// 这里的arg2代表长按的位置
				fileAdapter.photos.remove(arg2);// 移除数据
				listfile.remove(arg2);

				if (fileAdapter.photos.size() == 0)
				{
					gridview.setVisibility(View.GONE);
				}
				fileAdapter.notifyDataSetInvalidated();
				return true;
			}
		});

		gridview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				// TODO Auto-generated method stub
				LoadedImage uri = fileAdapter.getItem(arg2);
				// System.out.println(uri.getText());
				if (FileUtils.isPic(getLast(uri.getPicPath())))
				{
					ArrayList<String> picpathlist = new ArrayList<String>();
					Intent intent = new Intent(ReimburseApply.this, ShowPictureList.class);
					for (int i = 0; i < listfile.size(); i++)
					{
						if (FileUtils.isPic(listfile.get(i)))
						{
							picpathlist.add(listfile.get(i));
						}
					}

					for (int i = 0; i < picpathlist.size(); i++)
					{
						if (picpathlist.get(i).equals(uri.getPicPath()))
						{
							intent.putExtra("MOREN_INDEX", i);
						}
					}

					intent.putStringArrayListExtra("PICK_PATH_LIST", picpathlist);

					intent.putExtra("IS_BENDI", true);
					startActivity(intent);
				} else
				{
					Intent intent = new Intent(ReimburseApply.this, FileDetailActivity.class);
					intent.putExtra("FILE_URI", uri.getPicPath());
					intent.putExtra("FILE_NAME", getLast(uri.getPicPath()));
					intent.putExtra("IS_BENDI", true);
					startActivity(intent);
				}

				overridePendingTransition(R.anim.out_alpha, R.anim.enter_alpha);
			}
		});

		ImageView appendix_btn = (ImageView) reimburseView.findViewById(R.id.appendix_btn);
		appendix_btn.setOnClickListener(this);

		nextPeopleBg = (RelativeLayout) reimburseView.findViewById(R.id.next_people_bg);
		// 获取下一步处理人
		nextPeople = (TextView) reimburseView.findViewById(R.id.next_people);
		getNextPeople();

	}

	private void getNextPeople()
	{
		peoples_next = new ArrayList<PeopleNextData>();
		// 获取下一步处理人
		getNextPeople next = new getNextPeople();
		next.execute();
	}



	// 获取是否有可关联的借款申请
	private class IsHaveRelateBorrow extends AsyncTask<String, Integer, String>
	{

		// private ProgressDialog mProgress;
		MyLoadingDialog dialog;

		public IsHaveRelateBorrow() {
		}

		@Override
		protected void onPreExecute()
		{
			dialog = new MyLoadingDialog(context, null, "获取是否可申请信息...", false);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params)
		{
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try
			{
				response = LinkHelp.post(URLS.getIsHaveRelateBorrow(), null, false);

				if (response != null)
				{
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200)
					{
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine())
						{
							sb.append(s);
						}
						reader.close();
						result = sb.toString();

						System.out.println(result);
					}
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
			dialog.dimiss();
			if (result == null)
			{
				ToastHelp.doToast(context, "网络异常！");
				return;
			}

			try
			{
				JSONObject jsonObject = new JSONObject(result);

				if (result.contains(":false"))
				{
					ToastHelp.doToast(context, "无可关联的借款申请");
				} else
				{

					JSONObject obj = jsonObject.getJSONObject("oaBorrow");

					Intent intent = new Intent(context, TaskInfo.class);
					intent.putExtra("taskId", obj.getString("id"));
					intent.putExtra("processId", obj.getString("processInstanceId"));
					intent.putExtra("TASK_TYPE", "borrow");
					intent.putExtra("IS_TASK_TODO", false);
					intent.putExtra("IS_RELATATION", true);
					startActivityForResult(intent, SELECT_RELATION);
				}

			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

	}

	private String getLast(String path)
	{
		String a[] = path.split("/");
		return a[a.length - 1];
	}

	// 获取下一步处理人
	private class getNextPeople extends AsyncTask<String, Integer, String>
	{

		// private ProgressDialog mProgress;
		public getNextPeople() {
		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params)
		{
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try
			{
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				vs.add(new BasicNameValuePair("taskId", ""));
				vs.add(new BasicNameValuePair("projectName", xialaEdit.getText().toString()));
				response = LinkHelp.post(URLS.getNextWorkUser("ExpenseSale"), vs, false);

				if (response != null)
				{
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200)
					{
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine())
						{
							sb.append(s);
						}
						reader.close();
						result = sb.toString();

						System.out.println(result);
					}
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{

			if (result == null)
			{
				ToastHelp.doToast(context, "网络异常！");
				return;
			}

			JSONObject jsonObject;
			try
			{
				jsonObject = new JSONObject(result);
				if (jsonObject.isNull("code"))
				{
					String status = jsonObject.getString("status");
					if (status.equals("success"))
					{
						{
							if (result.contains("workUserInfo"))
							{
								JSONArray peoples = jsonObject.getJSONArray("workUserInfo");
								for (int i = 0; i < peoples.length(); i++)
								{
									PeopleNextData data = new PeopleNextData();
									JSONObject myJS = peoples.getJSONObject(i);
									data.setUserId(myJS.getString("userId"));
									data.setUserName(myJS.getString("userName"));
									data.setDepartmentId(myJS.getString("departmentId"));
									data.setDepartmentName(myJS.getString("departmentName"));
									data.setCompanyId(myJS.getString("companyId"));
									data.setCompanyName(myJS.getString("companyName"));
									data.setIsHead(myJS.getString("isHead"));
									data.setCode(myJS.getString("code"));
									peoples_next.add(data);
								}
								if (peoples_next.size() >= 1)
								{
									nextPeople.setText(peoples_next.get(0).getUserName() + "("
											+ peoples_next.get(0).getDepartmentName() + ")");
								} else
								{
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else if (result.contains("noNeedWorkUserId"))
							{
								if (jsonObject.getString("noNeedWorkUserId").equals("true"))
								{
									nextPeople.setText("下一步不需要处理人");
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else if (result.contains("msg"))
							{
								nextPeople.setText(jsonObject.getString("msg"));

								if (jsonObject.getString("msg").contains("不需要"))
								{
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else
							{
								System.out.println("Shit!服务器给的什么破数据");
							}

						}

					} else
					{
						String msg = jsonObject.getString("msg");
						// Toast.makeText(context, msg,
						// Toast.LENGTH_SHORT).show();
						ToastHelp.doToastInTop(context, msg);
						nextPeople.setText("空");
						nextPeopleBg.setVisibility(View.GONE);
					}

				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

	}

	public void refreshMoney()
	{
		try
		{
			double num = 0;
			for (int i = 0; i < childProjectList.size(); i++)
			{
				num += childProjectList.get(i).numOfmoney;
			}
			// editText4.setText("" + num);

			DecimalFormat nf = new DecimalFormat("#0.00");
			nf.setGroupingUsed(false);
			editText4.setText(nf.format(num));

			editText5.setText(DigitalTool.toBigMode(num));

			reimburseData.setMoney(num);

		} catch (Exception e)
		{
			// TODO: handle exception
		}

	}

	private void initBaseInfo()
	{
		// 申请人
		EditText applyEdit = (EditText) findViewById(R.id.editText1);
		applyEdit.setText(UserInfo.getUserInfor().getName());

		// 报销项目
		if (InternetKeep.getInstence().isSystemInfoLoad)
		{
			commonDialog = new CommonDialog(this);

			for (int i = 0; i < InternetKeep.getInstence().getProjectInfolist().size(); i++)
			{
				final View item = (View) LayoutInflater.from(context).inflate(R.layout.common_dialog_item, null);

				final TextView text = (TextView) item.findViewById(R.id.item_text);
				text.setText(InternetKeep.getInstence().getProjectInfolist().get(i).pur_Pay_Proj_Info);
				commonDialog.addView(item);
				xialaEdit.setText(InternetKeep.getInstence().getProjectInfolist().get(0).pur_Pay_Proj_Info);
				text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						xialaEdit.setText(text.getText().toString());

						commonDialog.dismiss();
						getNextPeople();
					}
				});
			}

		} else
		{
			// Toast.makeText(context, "报销项目加载失败", Toast.LENGTH_SHORT).show();
			ToastHelp.doToast(context, "报销项目加载失败");
		}

	}

	// 上传
	public void upload()
	{
		if (isCanUpload())
		{
			TextView relationInfo = (TextView) reimburseView.findViewById(R.id.title313);
			if (relationInfo.getText().toString().equals("") || relationInfo.getText().toString() == null)
			{
				new IsHaveRelation().execute();
			} else
			{
				UpdateLoadInfo upload = new UpdateLoadInfo(reimburseData);
				upload.execute();
			}

		}

	}

	public boolean isCanUpload()
	{
		EditText title = (EditText) findViewById(R.id.editText);
		String titleStr = title.getText().toString();
		if (titleStr == null || titleStr.equals(""))
		{
			// Toast.makeText(context, "标题不能为空", Toast.LENGTH_SHORT).show();
			ToastHelp.doToast(context, "标题不能为空");
			return false;
		} else
		{
			reimburseData.setTitle(titleStr);
		}

		if (xialaEdit.getText().toString().equals("报销项目"))
		{
			// Toast.makeText(context, "请选择报销项目", Toast.LENGTH_SHORT).show();
			ToastHelp.doToast(context, "请选择报销项目");
			return false;
		} else
		{
			reimburseData.setProjectName(xialaEdit.getText().toString());
		}

		reimburseData.getReimburseUseinfoList().clear();

		if (childProjectList.size() <= 0)
		{
			ToastHelp.doToast(context, "请填写至少一个项目用途");
			return false;
		}

		for (int i = 0; i < childProjectList.size(); i++)
		{
			ProjectChildData child = childProjectList.get(i);
			if (child.info == null || child.info.equals(""))
			{
				// Toast.makeText(context, "请填写项目用途",
				// Toast.LENGTH_SHORT).show();
				ToastHelp.doToast(context, "请填写项目用途");
				return false;
			}
			if (child.numOfmoney <= 0.0000000000000001)
			{
				// Toast.makeText(context, "请填写报销金额",
				// Toast.LENGTH_SHORT).show();
				ToastHelp.doToast(context, "请填写报销金额");
				return false;
			}

			reimburseData.getReimburseUseinfoList().add(child);
		}

		if (UserInfo.getUserInfor().isShenZhen())
		{
			if (xialaEdit1.getText().toString().contains("- -") || xialaEdit1.getText().toString() == null)
			{
				// Toast.makeText(context, "请选择报销项目",
				// Toast.LENGTH_SHORT).show();
				ToastHelp.doToast(context, "请选择是否有发票");
				return false;
			} else
			{
				// reimburseData.setProjectName(xialaEdit.getText().toString());
			}
		}

		return true;
	}

	@Override
	public void onClick(View arg0)
	{
		// TODO Auto-generated method stub
		int id = arg0.getId();
		// //隐藏软键盘
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(reimburseView.getWindowToken(), 0);

		// DigitalTool.lock((EditText)reimburseView.findViewById(R.id.editText));

		getCurrentFocus().clearFocus();
		EditText edit = (EditText) reimburseView.findViewById(R.id.edit_focuse_unable);
		edit.setFocusable(true);
		edit.requestFocus();

		switch (id) {
		case R.id.title_bar_btn_left:
			finish();
			break;

		case R.id.title_bar_btn_right:
			upload();
			break;
		case R.id.appendix_btn:
			Intent intent = new Intent(ReimburseApply.this, SelectPicActivity.class);
			intent.putExtra("type", "choosemore");
			intent.putExtra("IS_CHOOSE_FILE", true);
			startActivityForResult(intent, MenuActivity.SELECT_PHOTO);
			overridePendingTransition(R.anim.out_alpha, R.anim.enter_alpha);
			break;

		case R.id.title21:

		case R.id.btn_image1:
		{
			Window window = commonDialog.getWindow();
			window.setGravity(Gravity.BOTTOM);
			window.setWindowAnimations(R.style.pop_float_win_anim_style);
			commonDialog.show();
		}
			break;

		case R.id.title52:

		case R.id.btn_image2:
		{
			Window window = commonDialog1.getWindow();
			window.setGravity(Gravity.BOTTOM);
			window.setWindowAnimations(R.style.pop_float_win_anim_style);
			commonDialog1.show();
		}
			break;

		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK)
		{
			switch (requestCode) {

			case MenuActivity.SELECT_PHOTO:
				// ArrayList<String> files =new ArrayList<String>();
				listfileCatch.clear();
				listfileCatch = data.getStringArrayListExtra("files");
				listfile.addAll(listfileCatch);
				initGridView();
				break;
			case SELECT_RELATION:
				TextView relationInfo = (TextView) reimburseView.findViewById(R.id.title313);
				relationInfo.setText(data.getStringExtra("borrow_processid"));
				Id = data.getStringExtra("Id");
				break;

			default:
				break;
			}
		}

	}

	private void initGridView()
	{
		new AsyncLoadedImage().execute();

	}

	private String getBefore(String path)
	{
		String a[] = path.split("#");
		return a[0];
	}

	// 查询是否有可关联的借款
	private class IsHaveRelation extends AsyncTask<String, Integer, String>
	{
		// private ProgressDialog mProgress;
		MyLoadingDialog dialog;

		public IsHaveRelation() {

		}

		@Override
		protected void onPreExecute()
		{
			dialog = new MyLoadingDialog(ReimburseApply.this, null, "查询是否有可关联借款...", false);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params)
		{
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try
			{
				response = LinkHelp.post(URLS.getIsHaveRelate(), null, false);

				if (response != null)
				{
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200)
					{
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine())
						{
							sb.append(s);
						}
						reader.close();
						result = sb.toString();

						System.out.println(result);
					}
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
			dialog.dimiss();

			if (result == null || result.equals(""))
			{
				ToastHelp.doToast(context, "网络异常！");
				return;
			}

			if (result.contains("error"))
			{
				try
				{
					JSONObject obj = new JSONObject(result);
					ToastHelp.doToast(context, obj.getString("msg"));
				} catch (JSONException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else
			{

				try
				{
					JSONObject obj = new JSONObject(result);
					boolean iscan = obj.getBoolean("hasBorrow");
					if (iscan)
					{
						new AlertDialog.Builder(context).setMessage("你当前有可关联的借款申请")
								.setNegativeButton("不关联", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which)
									{
										UpdateLoadInfo upload = new UpdateLoadInfo(reimburseData);
										upload.execute();

									}
								}).setPositiveButton("关联", new DialogInterface.OnClickListener()

								{
									public void onClick(DialogInterface dialog, int whichButton)
									{
										new IsHaveRelateBorrow().execute();
									}
								}).show();

					} else
					{
						UpdateLoadInfo upload = new UpdateLoadInfo(reimburseData);
						upload.execute();
					}

				} catch (JSONException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}

	}

	/*
	 * 传送数据到服务器
	 */
	private class UpdateLoadInfo extends AsyncTask<String, Integer, String>
	{
		ReimburseData reimburseData;

		// private ProgressDialog mProgress;
		MyLoadingDialog dialog;

		public UpdateLoadInfo(ReimburseData reimburseData) {

			this.reimburseData = reimburseData;
		}

		@Override
		protected void onPreExecute()
		{
			dialog = new MyLoadingDialog(ReimburseApply.this, null, "上传中...", false);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params)
		{
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try
			{

				MultipartEntity multipartEntity = new MultipartEntity();
				for (String fileuri : listfile)
				{
					File file = new File(fileuri);
					FileBody filebody = new FileBody(file);
					multipartEntity.addPart(file.getName(), filebody);
				}

				multipartEntity.addPart("title", new StringBody(reimburseData.getTitle(), Charset.forName("UTF-8")));
				multipartEntity.addPart("projectName",
						new StringBody(reimburseData.getProjectName(), Charset.forName("UTF-8")));
				multipartEntity.addPart("purposeNum",
						new StringBody("" + reimburseData.getReimburseUseinfoList().size(), Charset.forName("UTF-8")));
				for (int i = 0; i < reimburseData.getReimburseUseinfoList().size(); i++)
				{
					multipartEntity.addPart("purposeInfo" + i,
							new StringBody(
									reimburseData.getReimburseUseinfoList().get(i).info + "_"
											+ reimburseData.getReimburseUseinfoList().get(i).numOfmoney,
									Charset.forName("UTF-8")));
				}
				multipartEntity.addPart("amount",
						new StringBody("" + reimburseData.getMoney(), Charset.forName("UTF-8")));
				if (xialaEdit1.getText().toString().equals(" - - ") || xialaEdit1.getText().toString() == null)
				{

				} else
				{
					String ishave = "";
					if (xialaEdit1.getText().toString().equals(getResources().getText(R.string.have_receipt)))
					{
						ishave = "yes";
					} else
					{
						ishave = "no";
					}
					multipartEntity.addPart("hasReceipt", new StringBody(ishave, Charset.forName("UTF-8")));
				}
				EditText remark = (EditText) reimburseView.findViewById(R.id.editText6);
				if (remark.getText().toString().equals("") || remark.getText().toString() == null)
				{

				} else
				{
					multipartEntity.addPart("remark",
							new StringBody(remark.getText().toString(), Charset.forName("UTF-8")));
				}

				TextView relationInfo = (TextView) reimburseView.findViewById(R.id.title313);
				if (relationInfo.getText().toString().equals("") || relationInfo.getText().toString() == null)
				{

				} else
				{
					// String borrowid =
					// getBefore(relationInfo.getText().toString());
					multipartEntity.addPart("borrowId", new StringBody(Id, Charset.forName("UTF-8")));
				}

				response = LinkHelp.UpPhotos(URLS.getReimburseStart(), multipartEntity, false);

				if (response != null)
				{
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200)
					{
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine())
						{
							sb.append(s);
						}
						reader.close();
						result = sb.toString();

						System.out.println(result);
					}
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
			JSONObject jsonObject;
			dialog.dimiss();

			try
			{

				if (null != result)
				{

					jsonObject = new JSONObject(result);
					if (jsonObject.isNull("code"))
					{
						String status = jsonObject.getString("status");
						UserInfo info = UserInfo.getUserInfor();
						if (status.equals("success"))
						{
							Toast.makeText(context, "提交成功", Toast.LENGTH_SHORT).show();

							finish();
						} else
						{
							String msg = jsonObject.getString("msg");
							// Toast.makeText(context, msg,
							// Toast.LENGTH_SHORT).show();
							ToastHelp.doToast(context, msg);
						}

					}
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

	}

	/*
	 * 异步加载缩略图到LoadedImage然后调用addImage方法更新Adapter
	 */
	class AsyncLoadedImage extends AsyncTask<Object, LoadedImage, Object>
	{
		@Override
		protected Object doInBackground(Object... params)
		{

			Bitmap bitmap = null;
			Bitmap newBitmap;
			for (int i = 0; i < listfileCatch.size(); i++)
			{
				String path = listfileCatch.get(i);

				File file = new File(path);
				if (file.exists())
				{
					System.out.println(path + "存在");
					if (FileUtils.isPic(path))
					{

						try
						{
							BitmapFactory.Options options = new BitmapFactory.Options();
							options.inSampleSize = 10;
							bitmap = BitmapFactory.decodeFile(path, options);
							newBitmap = ThumbnailUtils.extractThumbnail(bitmap, 120, 120);
							bitmap.recycle();
							if (newBitmap != null)
							{
								publishProgress(new LoadedImage(newBitmap, path));
							}
						} catch (Exception e)
						{
							e.printStackTrace();
						}

					} else
					{
						try
						{

							if (path.contains(".pdf"))
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pdf);
							} else if (path.contains(".txt"))
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.text);
							} else if (path.contains(".doc"))
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.word);
							} else if (path.contains(".zip"))
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.zip);
							} else if (path.contains(".xls"))
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.excel);
							} else
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.file);
							}
							newBitmap = ThumbnailUtils.extractThumbnail(bitmap, 120, 120);
							bitmap.recycle();
							if (newBitmap != null)
							{
								publishProgress(new LoadedImage(newBitmap, path));
							}
						} catch (Exception e)
						{
							e.printStackTrace();
						}

					}
				} else
				{
					listfile.remove(path);
				}

			}

			return null;
		}

		// 实时更新UI
		// onProgressUpdate()方法的参数对应于doInBackground中publishProgress方法的参数，同时也对应于
		// doInBackground的第二个参数
		@Override
		public void onProgressUpdate(LoadedImage... value)
		{
			addImage(value);
		}

		// 更新UI结束后的处理
		@Override
		protected void onPostExecute(Object result)
		{
			setProgressBarIndeterminateVisibility(false);
		}
	}

	/*
	 * 刷新Adapter
	 */
	private void addImage(LoadedImage... value)
	{
		for (LoadedImage image : value)
		{
			fileAdapter.addPhoto(image);
			gridview.setVisibility(View.VISIBLE);
			fileAdapter.notifyDataSetChanged();
		}
	}
}
